﻿@{
	ViewBag.Title = "Edit";
}

<link href="@Url.Content("~/Content/tulpagraphy.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/themes/base/jquery.ui.slider.css")" rel="stylesheet" type="text/css" />

<h2>Edit</h2>

<section id="tulpagraphy"  data-bind="css: { loading: loading() }">
    <section id="controls">
        <label for="map-name">Name: </label>
        <input type="text" data-bind="value: name, disable: loading" name="map-name" id="map-name" class="map-name"/>        
        <label for="grid-opacity-slider">Grid Opacity: </label>
        <div id="grid-opacity-slider" data-bind="slider: { value: gridOpacity, max: 1,  min: 0, step: .05 }"></div>
        <section class="rightAlign">
            <a class="button save" href="#" data-bind="click: saveMap">Save</a>
            <a class="button showPrintImageButton" href="#" data-bind="click: printImageModel.show">Print Image</a>                        
        </section>
    </section>
    <section id="map">
        <section class="map-container" id="mapContainer">
                <div class="map view" data-bind="style: { height: height().pixelSize() + 'px', width: width().pixelSize() + 'px' }">
                    <canvas class="background-layer" data-bind="attr: { height: height().pixelSize() + 'px', width: width().pixelSize() + 'px' }"></canvas>
                    <canvas class="embellishment-layer" data-bind="attr: { height: height().pixelSize() + 'px', width: width().pixelSize() + 'px' }"></canvas>
                    <svg class="selection-layer" xmlns="http://www.w3.org/2000/svg" version="1.1" data-bind="style: { 'stroke-opacity': gridOpacity }">
                        <polygon class="tile template" xmlns="http://www.w3.org/2000/svg"></polygon>
                    </svg>
                    <div class="loading-blocker">
                    </div>
                </div>
            <div class="loading-section">
                <div class="loading-image" ></div>
                <div class="message" data-bind="text: loadingMessage"></div>
            </div>
        </section>
    </section>
    <section id="toolbar" class="toolbar">
                    <section class="tool-set" data-bind="foreach: toolSets, accordion: {}">
                <a href="#" data-bind="text: title"></a>
                <section class="tools">
                    <ul data-bind="foreach: tools">
                        <li data-bind="event: { click: $root.setSelectedTool }, css: { selected: selected() }">
                            <div>
                                <img data-bind="attr: { src: imageUrl, alt: title }" src="#" alt="" />
                                <span data-bind="text: title"></span>
                            </div>
                        </li>
                    </ul>
                </section>
            </section>
    </section>
</section>
<section class="export-image-viewport" style="display: none;" onclick="{ return false; }">
	<div class="view">
		<div >
			<section class="image-container">
				<canvas class="image-canvas" height="1" width="1" data-bind="attr: { height: height().pixelSize() + 'px', width: width().pixelSize() + 'px' }"></canvas>
			</section>
			<ul class="actions">
				<li><input type="button" class="button" value="Close" data-bind="click: printImageModel.hide, disable: printImageModel.working" /></li>
				<li><input type="button" class="button" value="Refresh" data-bind="click: printImageModel.refreshCanvas, disable: printImageModel.working" /></li>
				<li><input type="button" class="button" value="Save Image" data-bind="click: printImageModel.downloadImage, disable: printImageModel.working" /></li>
				<li>
					<label for="filename">Filename: </label>
					<input type="text" name="filename" data-bind="value: printImageModel.filename, disable: printImageModel.working" />
				</li>
			</ul>
		</div>
		<div class="working-indicator" data-bind="css: { show: printImageModel.working() }"></div>
	</div>
</section>

<script src="@Url.Content("~/Scripts/models/map.js")"> </script>
<script>
	function makeSVG(tag, attrs) {
		var el = document.createElementNS('http://www.w3.org/2000/svg', tag);
		for (var k in attrs)
			el.setAttribute(k, attrs[k]);
		return el;
	};

	$(function () {
		function getId() {
			var id, temp;

			temp = window.location.href;

			if (temp) {
				temp = temp.split('/');

				if (temp) {
					temp = temp[temp.length - 1];

					if (temp && !temp.match(/\D/)) {
						id = parseInt(temp);
					}
				}
			}

			return id;
		};

		function constructBackgroundLayer(map, mapFactory) {
			mapFactory.constructMapBackgroundLayer(map, $("canvas.background-layer")[0]);
		};

		function constructEmbellishmentLayer(map, mapFactory) {
			mapFactory.constructMapEmbellishmentLayer(map, $("canvas.embellishment-layer")[0]);
		};

		function constructSelectionLayer(map, mapFactory) {
			var $selectionLayer = $('svg.selection-layer');
			var tileGroup = makeSVG('g', { class: 'active-tiles' });

			$selectionLayer.css('height', ((map.height().pixelSize()).toString() + 'px'));
			$selectionLayer.css('width', ((map.width().pixelSize()).toString() + 'px'));

			var points = map.pointsString();

			_.chain(map.tiles()).map(function (tile) {
				return makeSVG('polygon', {
					'points': points,
					'transform': 'translate(' + tile.x() + ', ' + tile.y() + ')',
					'data-x': tile.xIndex,
					'data-y': tile.yIndex
				});
			}).each(function (tile) {
				tileGroup.appendChild(tile);
			});

			$selectionLayer[0].appendChild(tileGroup);
			$selectionLayer.on('mousedown', '.active-tiles > polygon', function (e) { map.onMouseDownOnTile($(this), e); });
			$selectionLayer.on('mousemove', '.active-tiles > polygon', function (e) { window.tweakMouseEvent(e); return !map.onMouseOverTile($(this), e); });
			$selectionLayer[0].normalize();
		};

		// well, this is one way to do it...
		function initialize(map) {
			map.loading(true);

			map.loadingMessage('Loading background layer');
			setTimeout(function () {
				constructBackgroundLayer(map, mapFactory);

				map.loadingMessage('Loading embellishment layer');
				setTimeout(function () {
					constructEmbellishmentLayer(map, mapFactory);

					map.loadingMessage('Loading interaction layer');
					setTimeout(function () {
						constructSelectionLayer(map, mapFactory);
						editableMap.loading(false);
					}, 100);
				}, 100);
			}, 100);
		};

		var mapId = getId();

		if (!mapId) {
			alert('No map to load');
		}
		else {
			var map = mapFactory.constructMapViewModel(mapId);
			var editableMap = mapFactory.constructEditMapViewModel(map);
			ko.applyBindings(editableMap);

			initialize(editableMap);
		}
	});
</script>
<script type="text/javascript">
    ko.bindingHandlers.accordion = {
        init: function (element, valueAccessor) {
            var options = valueAccessor() || {};
            setTimeout(function () {
                $(element).accordion(options);
            }, 0);

            //handle disposal (if KO removes by the template binding)
            ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                $(element).accordion("destroy");
            });
        },
        update: function (element, valueAccessor) {
            var options = valueAccessor() || {};
            $(element).accordion("destroy").accordion(options);
        }
    };

    ko.bindingHandlers.slider = {
    	init: function (element, valueAccessor) {
    		var options = valueAccessor() || {};
    		var $element = $(element);

    		var moddedOptions = {
    			slide: function (e, ui) {
    				options.value(ui.value ? ui.value : .01);
				}
    		};

    		for (var i in options) { moddedOptions[i] = options[i]; }

    		if (moddedOptions.value) { moddedOptions.value = ko.utils.unwrapObservable(moddedOptions.value); }

    		setTimeout(function () {
    			$element.slider(moddedOptions);
    		}, 0);

    		//handle disposal (if KO removes by the template binding)
    		ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
    			$element.slider('destroy');
    		});
    	},
    	update: function (element, valueAccessor) {
    		var value = ko.utils.unwrapObservable(valueAccessor().value);
    		$(element).slider('value', value);
    	}
    };
</script>
<script src="/Scripts/libs/BlobBuilder.js"></script>
<script src="/Scripts/libs/FileSaver.custom.js"></script>
<script src="/Scripts/libs/canvas-toBlob.js"></script>